package net.htjs.juc.chapter06.atomicfieldupdater;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

@Slf4j
public class AtomicReferenceFieldUpdaterTest {

    public static void main(String[] args) {
        Student student = new Student("张三");
        AtomicReferenceFieldUpdater<Student, String> updater = AtomicReferenceFieldUpdater.newUpdater(Student.class, String.class, "name");
        updater.compareAndSet(student, "张三", "张三丰");
        log.info("{}", student.getName());
    }

}

class Student {
    //属性必须用volatile修饰，否则报异常 java.lang.IllegalArgumentException: Must be volatile type
    volatile String name;

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                '}';
    }
}
